package com.snail.auth;

import com.snail.auth.entity.AuthAuthority;
import com.snail.auth.entity.AuthRole;
import com.snail.auth.entity.AuthUser;
import com.snail.auth.entity.SecurityUser;
import com.snail.auth.service.AuthAuthorityService;
import com.snail.auth.service.AuthUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private AuthUserService authUserService;
    @Autowired
    private AuthAuthorityService authorityService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if ("sysadmin".equals(username)) {
            return sysAdmin(username);
        }
        AuthUser user = authUserService.findByLoginName(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在或失效");
        }
        if(user.getExpireDate()!=null && new Date().after(user.getExpireDate())){
            throw new AccountExpiredException("账号已过期");
        }
        if(user.getIsAccountNonLocked()!=null && user.getIsAccountNonLocked()==0){
            throw new LockedException("账号已锁定，请联系管理员");
        }
        List<AuthRole> roles = user.getRoles();
        Set<GrantedAuthority> grantedAuthoritys = new HashSet<>();
        Set<AuthAuthority> auths = new HashSet<>();
        for (AuthRole role : roles) {
            auths.addAll(role.getAuthorities());
        }
        StringBuilder authStrs = new StringBuilder();
        for (AuthAuthority auth : auths) {
            grantedAuthoritys.add(new SimpleGrantedAuthority(auth.getValue()));
            authStrs.append(auth.getValue()).append(",");
        }
        SecurityUser securityUser = new SecurityUser(user.getId(), user.getName(), user.getLoginName(), user.getPassword(), grantedAuthoritys);
        securityUser.setAuths("," + authStrs.toString());

        return securityUser;
    }

    /**
     * 准许超级管理员登录
     */
    public SecurityUser sysAdmin(String name) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String EncryptedPassword = bCryptPasswordEncoder.encode("123456");
        Set<GrantedAuthority> grantedAuthoritys = new HashSet<>();
        StringBuilder authStrs = new StringBuilder();
        for (AuthAuthority auth : authorityService.list()) {
            grantedAuthoritys.add(new SimpleGrantedAuthority(auth.getValue()));
            authStrs.append(auth.getValue()).append(",");
        }
        SecurityUser securityUser = new SecurityUser(0L, "超级管理员", name, EncryptedPassword, grantedAuthoritys);
        securityUser.setAuths(authStrs.toString());
        return securityUser;
    }

    public String createPWD(String rawPWD) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encryptedPassword = bCryptPasswordEncoder.encode(rawPWD);
        System.out.println("savePWD = " + encryptedPassword);
        return encryptedPassword;
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String EncryptedPassword = bCryptPasswordEncoder.encode("123456");
        System.out.println("savePWD = " + EncryptedPassword);
        System.out.println(bCryptPasswordEncoder.matches("123456", EncryptedPassword));
    }
}
